package com.right.health.app.ui.household.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.magic.basic.utils.CollectionUtil;
import com.magics.http.listener.OnHttpListener;
import com.magics.http.model.Request;
import com.magics.http.model.Response;
import com.right.health.app.R;
import com.right.health.app.base.BasePresenterFragment;
import com.right.health.app.bean.BloodSugarBean;
import com.right.health.app.bean.BloodSugarResponse;
import com.right.health.app.net.HouseholdApi;
import com.right.health.app.utils.LineChartUtil;
import com.right.health.app.utils.TimeUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class BloodSugarChartFragment extends BasePresenterFragment implements OnHttpListener {
    private final int HTTP_CODE_TYPE = 0;
    private static final String DAY_TYPE_KEY = "dat_type";

    private String[] mValues;

    private Map<String, Float> mXAxisMap;

    private LineChart mLineChart;

    private HouseholdApi mHouseholdApi;

    private String mType;

    private BloodSugarResponse mResponse;


    public static BloodSugarChartFragment newInstance(String type) {
        BloodSugarChartFragment fragment = new BloodSugarChartFragment();
        if (!TextUtils.isEmpty(type)) {
            Bundle bundle = new Bundle();
            bundle.putString(DAY_TYPE_KEY, type);
            fragment.setArguments(bundle);
        }
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle bundle, String s) {
        if (getArguments() != null) {
            mType = getArguments().getString(DAY_TYPE_KEY);
        }
        return layoutInflater.inflate(R.layout.fragment_chart_blood_sugar, viewGroup, false);
    }

    @Override
    public void findView() {
        mLineChart = (LineChart) findViewById(R.id.lineChart);
        LineChartUtil.setupLineChart(mLineChart);
        mLineChart = (LineChart) findViewById(R.id.lineChart);
        LineChartUtil.setupLineChart(mLineChart);
    }

    @Override
    public void initialize() {
        mHouseholdApi = new HouseholdApi();
        mHouseholdApi.setListener(this);
        mHouseholdApi.addRequestCode(HTTP_CODE_TYPE);
        mHouseholdApi.getBloodSugarByType(mType);
        switch (mType) {
            case BloodSugarResponse.TYPE_DAY:
                mValues = new String[]{"0", "3", "6", "9", "12", "15", "18", "21", "24"};
                LineChartUtil.getCommonXAxis(mLineChart, 9, 8, new ValueFormatter() {
                    @Override
                    public String getFormattedValue(float value) {
                        Log.i("TAG", "getFormattedValue: "+value+"  "+ mValues[(int) value]);

                        return value == 0 ? "" : String.format("%s:00", mValues[(int) value / 3]);
                    }
                });
                break;
            case BloodSugarResponse.TYPE_WEEK:
                mValues = TimeUtils.getPastWeek();
                LineChartUtil.getCommonXAxis(mLineChart, 8, 7, new ValueFormatter() {
                    @Override
                    public String getFormattedValue(float value) {
                             if (value==0)
                                 return "";
                        return mValues[(int) value-1];
                    }
                });
                break;
            case BloodSugarResponse.TYPE_MONTH:
                mValues = TimeUtils.getPastMonth();
                LineChartUtil.getCommonXAxis(mLineChart, 6, 30, new ValueFormatter() {
                    @Override
                    public String getFormattedValue(float value) {
                        if (value>0) {
                            return mValues[(int) value - 1];
                        }
                        return mValues[(int)value];
                    }
                });
                break;
        }
        mXAxisMap=new HashMap<>();
        for (int i = 0; i <mValues.length ; i++) {
            mXAxisMap.put(mValues[i], (float)i+1 );
        }
    }


    @Override
    public void refreshData() {
        super.refreshData();
        if (mHouseholdApi == null) {
            mHouseholdApi = new HouseholdApi();
            mHouseholdApi.setListener(this);
        }
        mHouseholdApi.addRequestCode(HTTP_CODE_TYPE);
        mHouseholdApi.getBloodSugarByType(mType);
    }


    @Override
    public void onResponse(Request request, Response response) {
        if (!isAdded()) {
            return;
        }
        if (request.requestCode == HTTP_CODE_TYPE) {
            if (response.targetData instanceof BloodSugarResponse) {
                mResponse = response.cast(BloodSugarResponse.class);
                refreshChart();
            }
        }
    }


    private void refreshChart() {
        double maxValue = 0;
        List<Entry> mLineValues = new ArrayList<>();
        if (mResponse != null && !CollectionUtil.isEmpty(mResponse.sugars)) {
            Collections.sort(mResponse.sugars, new Comparator<BloodSugarBean>() {
                @Override
                public int compare(BloodSugarBean t, BloodSugarBean t1) {
                    if (t1.getCreatetime() == null || t.getCreatetime() == null) {
                        return -1;
                    }
                    return (Float.valueOf(t.getCreatetime()) > Float.valueOf(t1.getCreatetime())) ? 1 : -1;
                }
            });
            for (BloodSugarBean info : mResponse.sugars) {
                if (info == null || info.getCreatetime() == null || info.getSugarvalue() == null) {
                    continue;
                }
               String key = "";
                if (TextUtils.equals(mType,BloodSugarResponse.TYPE_DAY)){
                    key =  TimeUtils.getHour(info.getCreatetime())+"";

                }else {
                    key = TimeUtils.getMonthAndDay(Long.valueOf(info.getCreatetime()));

                }
         /*       switch () {
                    case BloodSugarResponse.TYPE_DAY:
                        break;
                    case BloodSugarResponse.TYPE_WEEK:
                    case BloodSugarResponse.TYPE_MONTH:
                        break;
                }*/
                float x = 0;
                float value = 0;
                try {
                    if (mXAxisMap.containsKey(key)) {
                        x = mXAxisMap.get(key);
                    }else {
                        continue;
                    }
                    value = Float.valueOf(info.getSugarvalue());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                maxValue = Math.max(maxValue, Math.ceil(value));

                mLineValues.add(new Entry(x, value));
            }

            LineDataSet line = LineChartUtil.createLine(mLineValues, getResources().getColor(R.color.color_09C3BE));
            LineChartUtil.getCommonYAxis(mLineChart, 5, (int) Math.ceil(maxValue), null);
            LineChartUtil.refresh(mLineChart, line);
        } else {
            LineChartUtil.refresh(mLineChart);
        }
    }
}
